package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        Date date = new Date();
        serviceItem.setCreateTime(date);
        //默认状态为下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        //是套餐才审核
        if (serviceItem.getCarPackage()) {
            //设置为初始化状态
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            //不是套餐，审核状态设置为无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }



    @Override
    public void saleOn(Long id) {
        //满足什么条件才允许上架
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        //为空或上架就抛出异常
        if (serviceItem==null||ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw new BusinessException("参数异常");
        }
        //普通服务单项---直接上架
        if (!serviceItem.getCarPackage()){
            //改变状态
            serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
        }else {
            //如果是套餐---需要审核通过状态才可以上架
            if (ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
                serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);

            }else {
                throw new BusinessException("服务套餐必须审核之后才能上架");
            }
        }


    }

    @Override
    public void saleOff(Long id) {
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        //为空或上架就抛出异常
        if (serviceItem==null||ServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())){
            throw new BusinessException("参数异常");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public TablePageInfo<ServiceItem> selectAllSaleOnList(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectAllSaleOnList(qo));
    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        //根据传入的id查询服务项，服务项状态处于初始化才能进行审核逻辑
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        //满足审核条件
        if (serviceItem==null || !serviceItem.getCarPackage() ||
        !ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("参数异常，不允许进行审核");
        }
        //套餐服务状态改为审核中
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
        //保存套餐审核记录对象
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(id);
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());
        carPackageAudit.setCreateTime(new Date());
        carPackageAudit.setCreator(ShiroUtils.getLoginName());
        carPackageAudit.setAuditorId(director);
        carPackageAudit.setBpmnInfoId(bpmnInfoId);
        carPackageAudit.setInfo(info);
        carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        carPackageAuditService.save(carPackageAudit);
        //启动服务定价审核流程
        HashMap<String, Object> map = new HashMap<>();
        //指定审核的人
        if (director!=null) {
            map.put("director",director);
        }
        if (finance!=null) {
            map.put("finance",finance);
        }
        //2.指定审核价格
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        //3.绑定businessKey
        String businessKey = carPackageAudit.getId().toString();
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);

        //启动流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(),
                businessKey, map);
        //更新记录实例id
        carPackageAudit.setInstanceId(processInstance.getId());
        carPackageAuditService.updateInstanceId(carPackageAudit.getId(),processInstance.getId());


    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer auditStatus) {
        serviceItemMapper.changeAuditStatus(serviceItemId,auditStatus);
    }
}
